<?php

namespace App\Api\Controllers;


use App\Api\Validate\DeliveryValidate;
use App\Api\Validate\MiniUserValidate;
use App\Events\Delivery;
use App\Models\RoomSendHis;
use Illuminate\Http\Request;
use Illuminate\Queue\Jobs\Job;
use Illuminate\Support\Facades\DB;

class DeliveryController extends BaseController
{

    /**
     * 送物记录（订单列表）
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $pageNum  = (int)$request->get("page_num");
        $pageSize = (int)$request->get("page_size", 10);
        $model = DB::table('room_send_his')
            ->leftjoin('goods', 'goods.id', '=', 'room_send_his.goods_id')
            ->where([
                ['room_send_his.openid' , $this->user->openid],
            ])
            ->orderBy('room_send_his.id', 'DESC')
            ->paginate($pageSize,
                ['room_send_his.id','goods.name','room_send_his.order_at','room_send_his.num','room_send_his.send_status'],
                "page",
                $pageNum);

        $list = $model->getCollection();
        return Success(10100, [
            "data"      => $list,
            "page_info" => [
                'current' => $pageNum, 'page_size' => $pageSize, "count" => $model->total(),
                "pages"   => $model->lastPage()
            ]
        ]);
        return Success(11000, $data);
    }


    /**
     * 下单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function order(Request $request)
    {
        $params = $request->all();
        (new DeliveryValidate())->order($request->all());

        // 判断是否在入住期间
        $living = (new MiniUserValidate())->checkLiving($this->user->openid);

        $params['openid']  = $this->user->openid;
        $params['room_id'] = $living->room_id;

        // 判断库存
        (new DeliveryValidate())->goodAndStockCheck($params);

        $result = (new RoomSendHis())->add($params);
        if (!$result) {
            return Failed(50000,  ["File" => __CLASS__, "Action" => __FUNCTION__, "Line" => __LINE__]);
        }

        // 发送消息
        event(new Delivery($result));

        return $this->success(200, '下单成功');
    }


    public function cancel(Request $request)
    {
        $params = $request->all();

        $record = (new DeliveryValidate())->baseCheck($params);

        // 修改订单状态
        $result = (new RoomSendHis())->setSendStatus($record, RoomSendHis::SEND_STATUS_CANCEL);
        if (!$result) {
            return Failed(50000,  ["File" => __CLASS__, "Action" => __FUNCTION__, "Line" => __LINE__]);
        }

        // TODO 推送取消消息

        return $this->success(200, '订单已取消');
    }
}
